package com.hzz.framework.fileServer.baidu.ueditor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.io.CharStreams;
import com.hzz.framework.fileServer.baidu.ueditor.define.ActionMap;
import com.hzz.framework.fileServer.config.FileServerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置管理器
 *
 * @author hancong03@baidu.com
 */
@Component
public class ConfigManager {
    private static final String configFileName = "config.json";
    // 涂鸦上传filename定义
    private final static String SCRAWL_FILE_NAME = "scrawl";
    // 远程图片抓取filename定义
    private final static String REMOTE_FILE_NAME = "remote";
    @Autowired
    private FileServerProperties fileServer;
    private String rootPath;
    private String originalPath;
    private String contextPath;
    private String parentPath = null;
    private JSONObject jsonConfig = null;

    /**
     * Get rootPath from request,if not,find it from conf map.
     *
     * @param request
     * @param conf
     * @return
     * @author Ternence
     * @create 2015年1月31日
     */
    public static String getRootPath(HttpServletRequest request, Map<String, Object> conf) {
        Object rootPath = request.getAttribute("rootPath");
        if (rootPath != null) {
            return rootPath + "" + File.separatorChar;
        } else {
            return conf.get("rootPath") + "";
        }
    }
//	/**
//	 * 配置管理器构造工厂
//	 * @param rootPath 服务器根路径
//	 * @param contextPath 服务器所在项目路径
//	 * @param uri 当前访问的uri
//	 * @return 配置管理器实例或者null
//	 */
//	public static ConfigManager getInstance ( String rootPath, String contextPath, String uri ) {
//
//		try {
//			return new ConfigManager(rootPath, contextPath, uri);
//		} catch ( Exception e ) {
//			return null;
//		}
//
//	}

    /*
     * 通过一个给定的路径构建一个配置管理器， 该管理器要求地址路径所在目录下必须存在config.properties文件
     */
    public ConfigManager init(String rootPath, String contextPath, String uri) throws IOException {
        rootPath = rootPath.replace("\\", "/");
        this.contextPath = contextPath;
        this.rootPath = rootPath;
        this.originalPath = this.rootPath + uri;
        this.initEnv();
        return this;
    }

    // 验证配置文件加载是否正确
    public boolean valid() {
        return this.jsonConfig != null;
    }

    public JSONObject getAllConfig() {

        return this.jsonConfig;

    }

    public Map<String, Object> getConfig(int type) {

        Map<String, Object> conf = new HashMap<String, Object>();
        String savePath = null;

        switch (type) {
            case ActionMap.UPLOAD_FILE:
                conf.put("isBase64", "false");
                conf.put("maxSize", this.jsonConfig.getLong("fileMaxSize"));
                conf.put("allowFiles", this.getArray("fileAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("fileFieldName"));
                savePath = this.jsonConfig.getString("filePathFormat");
                break;

            case ActionMap.UPLOAD_IMAGE:
                conf.put("isBase64", "false");
                conf.put("maxSize", this.jsonConfig.getLong("imageMaxSize"));
                conf.put("allowFiles", this.getArray("imageAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("imageFieldName"));
                savePath = this.jsonConfig.getString("imagePathFormat");
                break;

            case ActionMap.UPLOAD_VIDEO:
                conf.put("maxSize", this.jsonConfig.getLong("videoMaxSize"));
                conf.put("allowFiles", this.getArray("videoAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("videoFieldName"));
                savePath = this.jsonConfig.getString("videoPathFormat");
                break;

            case ActionMap.UPLOAD_SCRAWL:
                conf.put("filename", ConfigManager.SCRAWL_FILE_NAME);
                conf.put("maxSize", this.jsonConfig.getLong("scrawlMaxSize"));
                conf.put("fieldName", this.jsonConfig.getString("scrawlFieldName"));
                conf.put("isBase64", "true");
                savePath = this.jsonConfig.getString("scrawlPathFormat");
                break;

            case ActionMap.CATCH_IMAGE:
                conf.put("filename", ConfigManager.REMOTE_FILE_NAME);
                conf.put("filter", this.getArray("catcherLocalDomain"));
                conf.put("maxSize", this.jsonConfig.getLong("catcherMaxSize"));
                conf.put("allowFiles", this.getArray("catcherAllowFiles"));
                conf.put("fieldName", this.jsonConfig.getString("catcherFieldName") + "[]");
                savePath = this.jsonConfig.getString("catcherPathFormat");
                break;

            case ActionMap.LIST_IMAGE:
                conf.put("allowFiles", this.getArray("imageManagerAllowFiles"));
                conf.put("dir", this.jsonConfig.getString("imageManagerListPath"));
                conf.put("count", this.jsonConfig.getInteger("imageManagerListSize"));
                break;

            case ActionMap.LIST_FILE:
                conf.put("allowFiles", this.getArray("fileManagerAllowFiles"));
                conf.put("dir", this.jsonConfig.getString("fileManagerListPath"));
                conf.put("count", this.jsonConfig.getInteger("fileManagerListSize"));
                break;
        }

        conf.put("savePath", savePath);
        conf.put("rootPath", this.rootPath);

        return conf;

    }

    private void initEnv() throws IOException {

        File file = new File(this.originalPath);

        if (!file.isAbsolute()) {
            file = new File(file.getAbsolutePath());
        }

        this.parentPath = file.getParent();

//		String configContent = this.readFile( this.getConfigPath() );
        ClassLoader classloader = Thread.currentThread().getContextClassLoader();
        String configContent = CharStreams.toString(new InputStreamReader(classloader.getResourceAsStream("config.json")));//this.readFile(this.getConfigPath());
        try {
            JSONObject jsonConfig = JSON.parseObject(configContent);
            jsonConfig.put("fileMaxSize", fileServer.getFileSize().getFile() * 1024 * 1024);
            jsonConfig.put("fileAllowFiles", fileServer.getFileExt().getFile().split("\\,"));
            jsonConfig.put("imageMaxSize", fileServer.getFileSize().getImage() * 1024 * 1024);
            jsonConfig.put("imageAllowFiles", fileServer.getFileExt().getImage().split("\\,"));
            jsonConfig.put("videoMaxSize", fileServer.getFileSize().getMedia() * 1024 * 1024);
            jsonConfig.put("videoAllowFiles", fileServer.getFileExt().getMedia().split("\\,"));
            jsonConfig.put("scrawlMaxSize", fileServer.getFileSize().getImage() * 1024 * 1024);
            jsonConfig.put("catcherMaxSize", fileServer.getFileSize().getImage() * 1024 * 1024);
            jsonConfig.put("catcherAllowFiles", fileServer.getFileExt().getImage().split("\\,"));
            jsonConfig.put("imageManagerAllowFiles", fileServer.getFileExt().getImage().split("\\,"));
            jsonConfig.put("fileManagerAllowFiles", fileServer.getFileExt().getFile().split("\\,"));
            this.jsonConfig = jsonConfig;
        } catch (Exception e) {
            this.jsonConfig = null;
        }

    }

    private String getConfigPath() {
        String path = this.getClass().getResource("/").getPath() + ConfigManager.configFileName;
        if (new File(path).exists()) {
            return path;
        } else {
            return this.parentPath + File.separator + ConfigManager.configFileName;
        }
    }

    private String[] getArray(String key) {
        JSONArray jsonArray = this.jsonConfig.getJSONArray(key);
        String[] result = new String[jsonArray.size()];

        for (int i = 0, len = jsonArray.size(); i < len; i++) {
            result[i] = jsonArray.getString(i);
        }
        return result;

    }

    // 过滤输入字符串, 剔除多行注释以及替换掉反斜杠
    private String filter(String input) {
        return input.replaceAll("/\\*[\\s\\S]*?\\*/", "");

    }

}
